package com.ep.thirdPlatformProject.job.jobhandler;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.ObjectUtil;
import com.ep.thirdPlatformProject.erp.helper.ErpDayCostHelper;
import com.ep.thirdPlatformProject.job.service.MayCurToErpService;
import com.ep.thirdPlatformProject.maycur.common.Constant;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Map;


/**
 * 每刻 to ERP 的定时任务
 *
 * @author Karl
 * @date 2024/04/01
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MayCurToERPJob {


    private final ErpDayCostHelper erpDayCostHelper;

    private final MayCurToErpService mayCurToErpService;

    @XxlJob("mayCurPayAmountJob")
    public void doJob() {
        try {
            StopWatch watch = DateUtil.createStopWatch();
            watch.start("任务开始");
            // 获取参数
            String jobParam = XxlJobHelper.getJobParam();
            DateTime dateTime = resolveDateTimeFromParam(jobParam);

            Map<String, BigDecimal> totalAmountMap = mayCurToErpService.getTotalAmountMap(dateTime);
            BigDecimal dayAmount = totalAmountMap.get(Constant.DAY_TOTAL_EXPENSE_AMOUNT);
            BigDecimal monthAmount = totalAmountMap.get(Constant.MONTH_TOTAL_EXPENSE_AMOUNT);
            BigDecimal yearAmount = totalAmountMap.get(Constant.YEAR_TOTAL_EXPENSE_AMOUNT);
            XxlJobHelper.log("今日费用合计：{}，本月费用合计：{}，本年费用合计：{}", dayAmount, monthAmount, yearAmount
            );


            String response = erpDayCostHelper.sendPostRequest(
                    DateUtil.format(dateTime, "yyyy-MM-dd"),
                    dayAmount.toString(),
                    monthAmount.toString(),
                    yearAmount.toString()
            );
            watch.stop();
            XxlJobHelper.log("任务结束，处理任务耗时：{}ms", watch.getTotalTimeMillis());
            XxlJobHelper.handleSuccess(response);
        } catch (Exception e) {
            log.error("每刻定时任务执行失败，{}", e.getMessage(), e);
            XxlJobHelper.handleFail(String.format("每刻定时任务执行失败，%s", e.getMessage()));
        }
    }


    /**
     * 解析或获取当前日期时间
     *
     * @param params 日期时间字符串参数
     * @return {@link DateTime}
     */
    private DateTime resolveDateTimeFromParam(String params) {
        DateTime dateTime = null;
        try {
            if (ObjectUtil.isNull(params) || params.trim().isEmpty()) {
                dateTime = DateTime.now();
                XxlJobHelper.log("使用默认时间：{},标准化：{}", dateTime, DateUtil.date(dateTime));
            } else {
                DateTimeFormatter[] formatters = {
                        DatePattern.NORM_DATETIME_FORMATTER,
                        DatePattern.CHINESE_DATE_TIME_FORMATTER,
                        DatePattern.NORM_DATE_FORMATTER,
                        DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss"),
                        DateTimeFormatter.ofPattern("MM/dd/yyyy"),
                        DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),
                        DateTimeFormatter.ofPattern("yyyy/MM/dd")
                };
                boolean parsed = false;
                for (DateTimeFormatter formatter : formatters) {
                    try {
                        dateTime = DateUtil.parse(params, formatter);
                        XxlJobHelper.log("成功解析参数时间：{}，使用格式：{}", dateTime, formatter);
                        parsed = true;
                        break;
                    } catch (DateTimeParseException e) {
                        // Continue to next formatter if parsing fails
                        log.error("日期处理失败了,{}",e.getMessage());
                    }
                }
                if (!parsed) {
                    throw new DateTimeParseException("Unable to parse input parameter", params, 0);
                }
            }
            return dateTime;
        } catch (DateTimeParseException e) {
            // 日志记录优化：区分异常类型，提供更丰富的错误上下文
            log.error("解析日期时间失败: 参数格式不正确, 参数: {}", params, e);
            XxlJobHelper.log("解析日期时间失败: 参数格式不正确, 参数: {}", params, e);
            throw new RuntimeException("解析日期时间失败: 参数格式不正确, 参数: " + params, e);
        } catch (Exception e) {
            // 处理预期之外的异常
            log.error("解析日期时间时发生未知异常, 参数: {}", params, e);
            XxlJobHelper.log("解析日期时间时发生未知异常, 参数: {}", params, e);
            throw new RuntimeException("解析日期时间时发生未知异常, 参数: " + params, e);
        }
    }

}
